<template>
  <el-container>
    <!-- 小说展示区 -->
    <el-main>
      <el-row class="book-list">
        <div v-for="(book, index) in books" :key="index" class="book-item">
          <el-card shadow="hover" class="book-card">
            <div class="image-container">
              <img :src="book.coverImageUrl" alt="book image" class="book-image" />
            </div>
            <h3 class="book-title">{{ book.title }}</h3>

            <!-- 下拉菜单 -->
            <el-dropdown class="book-dropdown" trigger="click" @command="handleCommand(book, $event)">
              <span class="el-dropdown-link">
                <i class="el-icon-more">...</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit-description">更改介绍</el-dropdown-item>
                  <el-dropdown-item command="chapter-details">章节详细</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-card>
        </div>
      </el-row>

      <!-- 分页组件 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pagination.totalRecords"
        :page-size="pagination.size"
        :current-page="pagination.page"
        @current-change="handlePageChange"
        style="text-align: center; margin-top: 20px;"
      />
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';

// 定义选择的书籍
const selectBook = ref<any>(null);
const userinfo = useUserStore().userInfo;
// 书籍列表
const books = ref([]);

// 分页数据
const pagination = ref({
  page: 1,         // 当前页
  size: 8,        // 每页条数
  totalPages: 1,   // 总页数
  totalRecords: 0  // 总记录数
});


const authorId =userinfo.id;  

// 获取书籍数据
const fetchBooks = (pageNum: number, pageSize: number) => {
  // 构建请求路径和查询参数
  const url = `/api/books/author/${authorId}?pageNum=${pageNum}&pageSize=${pageSize}`;
  
  axios.get(url)
    .then(response => {
      const data = response.data.data;
      books.value = data.listData;

      // 更新分页数据
      pagination.value.page = data.page;
      pagination.value.size = data.size;
      pagination.value.totalPages = data.totalPages;
      pagination.value.totalRecords = data.totalRecords;
    })
    .catch(error => {
      console.error('Error fetching books:', error);
      ElMessage({ message: '加载书籍数据失败', type: 'error' });
    });
};

// 页面挂载时请求数据
onMounted(() => {
  fetchBooks(pagination.value.page, pagination.value.size);
});

// 处理分页切换
const handlePageChange = (newPage: number) => {
  pagination.value.page = newPage;
  fetchBooks(newPage, pagination.value.size); // 请求新页数据
};
const emit = defineEmits(['submit']);
const submitbook = () => {
  if (selectBook.value.id != null) {
    emit('submit', selectBook.value);
    selectBook.value = ref();
  }
};
// 处理下拉菜单的命令事件
const handleCommand = (book: { title: string, id: number }, command: string) => {
  selectBook.value = book;
  switch (command) {
    case 'edit-description':
      console.log(`更改id为${book.id} 标题为 ${book.title} 的介绍1`);
      break;
    case 'chapter-details':
      console.log(`查看id为${book.id} 标题为 ${book.title}的章节详细`);
      submitbook()
      break;
    case 'delete':
      handleDeleteById();
      console.log(`删除id为${book.id} 标题为 ${book.title}`);
      break;
    default:
      break;
  }
};

// 删除书籍方法
const handleDeleteById = () => {
  const data = selectBook.value.id;
  axios.delete(`/api/books/delete/${data}`)
    .then(response => {
      if (response.data.code === 200) {
        books.value = books.value.filter(book => book.id !== data);
        ElMessage({ message: "删除书本成功", type: 'success' });
      }
    })
    .catch(_ => {
      ElMessage({ message: "删除书籍时出现了一个未知错误", type: 'error' });
    });
};
</script>

<style scoped>
.book-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
  width: 100%;
  overflow: auto;
}

.book-item {
  width: auto;
  text-align: center;
}

.book-card {
  padding: 10px;
}

.image-container {
  width: 120px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.book-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.book-title {
  margin-top: 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

/* 下拉菜单样式 */
.book-dropdown {
  font-size: 18px;
  cursor: pointer;
}

.el-dropdown-link {
  cursor: pointer;
}
</style>
